package Core;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;

import Logic.CreateClientCmd;
import com.lmax.disruptor.RingBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledDirectByteBuf;
import io.netty.buffer.UnpooledUnsafeDirectByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import microgame.airplane.proto.Login;
import microgame.airplane.proto.MsgTypeOuterClass;
import microgame.airplane.proto.ProtoPacker;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

        if (frame instanceof TextWebSocketFrame) {
            String request = ((TextWebSocketFrame) frame).text();
            request += "| (This is java netty server echo)";
            ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.US)));

        } else if (frame instanceof BinaryWebSocketFrame) {
            //这里接受到protobuf信息，我们把它做成一个NetData结构，送入NetDataQueue供Game解析
            short size = frame.content().readShort();
            short id = frame.content().readShort();
            byte[] content =  new byte[size];
            frame.content().getBytes(NetData.PROTOHEADSIZE, content);

            NetData data = new NetData(ctx.channel(), content, NetDataType.Proto, id);
            NetDataQueue.Instance().getQueue().put(data);
        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NetData data = new NetData(ctx.channel(), null, NetDataType.Custom, 90000);
        NetDataQueue.Instance().getQueue().put(data);
        ctx.fireChannelInactive();
    }
}